﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;

namespace DataVisualizers
{
    public class ImageTools
    {
        private static byte[] _tempArray;

        /// <summary>
        /// Writes image data to a grayscale bitmap array 
        /// </summary>
        /// <param name="imageData"></param>
        /// <param name="output"></param>
        /// <returns></returns>
        public static void WriteToGrayscaleBitmap(double[] imageData, ref Bitmap output)
        {
            if (imageData.Length != output.Width * output.Height)
                throw new ArgumentException("Input vector size does not correspond to the specified height and width.");

            var min = imageData.Min();
            var max = imageData.Max();

            double difference = max - min;

            Rectangle rect = new Rectangle(0, 0, output.Width, output.Height);
            BitmapData testdata = output.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);

            int dest = (int)testdata.Scan0;
            if (_tempArray == null || _tempArray.Length != imageData.Length * 4)
                _tempArray = new Byte[imageData.Length * 4];
            // todo: understand performance hit using Select
            for (int i = 0; i < imageData.Length; ++i)
            {
                _tempArray[i * 4] =
                    _tempArray[i * 4 + 1] =
                    _tempArray[i * 4 + 2] =
                    _tempArray[i * 4 + 3] = (Byte)((imageData[i] - min) / difference * 255);
            }

            System.Runtime.InteropServices.Marshal.Copy(_tempArray, 0, (IntPtr)dest, _tempArray.Length);

            output.UnlockBits(testdata);
        }
    }
}
